package com.template.ejb.service.bean;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.template.ejb.rest.dto.MathDTO;

@MessageDriven(name = "ProcessMessageBean", activationConfig = {
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/myQueue") })
public class ProcessMessageBean implements MessageListener {

	private static Log log = LogFactory.getLog(ProcessMessageBean.class);

	@Resource
	private MessageDrivenContext context;

	public void onMessage(Message message) {
		try {
			if (message instanceof ObjectMessage) {
				ObjectMessage objMessage = (ObjectMessage) message;
				Object obj = objMessage.getObject();
				if (obj instanceof MathDTO) {

					MathDTO mathDTO = (MathDTO) obj;

					log.info("==> xxxxxx " + (mathDTO.getA() + mathDTO.getB()));

					Thread.sleep(mathDTO.getA() + mathDTO.getB());

					log.info("<== Work done!");

				} else {
					log.error("Expecting MathDTO in Message");
				}
			} else {
				log.error("Expecting Object Message");
			}
		} catch (Throwable t) {
			log.error(t.getMessage(), t);
			context.setRollbackOnly();
		}

	}

}
